package giit.computerbase.server;

import giit.computerbase.dao.SQL;
import giit.computerbase.dao.SQLFactory;
import giit.computerbase.util.Application;
import giit.computerbase.util.Hash;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * User: tum0r
 * Package Name: giit.computerbase.server
 * Time: 2018/11/11 Sunday 11:59:25
 */
public class UserServer {
    private SQL sql;
    private Hash hash;

    public UserServer() {
        try {
            sql = SQLFactory.getSQL();
            sql.open((String) Application.getConfig().databaseConfig.get("address"),
                    (int) Application.getConfig().databaseConfig.get("port"),
                    Application.DATABASE_NAME,
                    (String) Application.getConfig().databaseConfig.get("encode"),
                    (String) Application.getConfig().databaseConfig.get("user"),
                    (String) Application.getConfig().databaseConfig.get("password"));
            hash = new Hash();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public boolean register(String user, String organizationName, String password) {
        boolean flag = false;
        ArrayList<HashMap<String, Object>> data = sql.query("select id from organization where name=?", new Object[]{organizationName});
        if (data.size() == 1) {
            flag = sql.add("insert into user values(?,?,?,?,?,?)", new Object[]{Application.getUUID(), user, data.iterator().next().get("id"), hash.encryption(hash.encryption(password, Hash.SHA256), Hash.MD5), Application.USER_TYPES[0][0], 1});
        }
        return flag;
    }

    public boolean changeInforamation(String id, String userName, String password, String organizationID, String userTypeID, int state) {
        boolean flag = false;
        StringBuffer command = new StringBuffer();
        command.append("update set name=?,organization_id=?,user_type_id=?,state=?");
        if (password != null && !password.equals("")) {
            command.append(",password=?");
        }
        command.append(" where id=?");
        if (password != null && !password.equals("")) {
            flag = sql.alter(command.toString(), new Object[]{userName, organizationID, userTypeID, state, hash.encryption(hash.encryption(password, Hash.SHA256), Hash.MD5), id});
        } else {
            flag = sql.alter(command.toString(), new Object[]{userName, organizationID, userTypeID, state, id});
        }
        return flag;
    }

    public ArrayList<HashMap<String, Object>> getUsers() {
        return sql.query("select * from user", null);
    }

    public boolean delete(String user){
        return sql.delete("delete from user where name=?",new Object[]{user});
    }
}
